<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>管理员管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card> 
      <!-- layout布局 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入要查找的管理员名或账号 "
            v-model="queryInfo.query"
            clearable
            @clear="getAdminList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getAdminList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加管理员</el-button
          >
        </el-col>
      </el-row>

      <!-- 表单 -->
      <el-table
        ref="multipleTable"
        :data="adminList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="index" width="55" label="#"> </el-table-column>
        <el-table-column prop="adminList" label="头像">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.url"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="adminId" label="管理员id"> </el-table-column>
        <el-table-column prop="adminname" label="账号"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <!-- 这里指定了一个宽度，才能撑下三个按钮 -->
        <el-table-column
          prop="address"
          label="操作"
          show-overflow-tooltip
          width="180px"
        >
          <!-- 这里也是使用了 插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteById(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加信息的对话框 -->
    <el-dialog
      title="添加管理员"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="管理员名" prop="adminname">
          <el-input v-model="addForm.adminname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <!-- 上传头像 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost/admin/uploadPic"
            :show-file-list="false"
            name="adminImg"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSuccess">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改信息的对话框 -->
    <el-dialog
      title="修改管理员信息"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
    >
      <el-form
        label-width="100px"
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
      >
        <el-form-item label="管理员名">
          <el-input v-model="editForm.adminname" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <!-- 上传头像 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost/admin/uploadPic"
            :show-file-list="false"
            name="adminImg"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl2" :src="imageUrl2" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSuccess">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
export default {
  created() {
    this.getAdminList();
  },
  methods: {
    async getAdminList() {
      const { data: res } = await this.$http.get(
        `/admin/${this.queryInfo.pagenum}/${this.queryInfo.pagesize}?adminname=` +
          this.queryInfo.query
      );
      console.log(res, "分页获取到的管理员数据");
      this.adminList = res.data.records;
      this.total = res.data.total;
    },
    /* 清空添加表单的对话框 监听*/
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    addSuccess() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post("/admin/addAdmin", {
            adminname: this.addForm.adminname,
            password: this.addForm.password,
            email: this.addForm.email,
            url:this.url
          });
          console.log(res, "我是添加成功之后的返回值");
          if (res.flag == true) {
            this.$message.success(res.msg);
            this.addDialogVisible = false;
            this.getAdminList();
          } else {
            this.$message.error(res.msg);
          }
        }
      });
    },
    async showEditDialog(row) {
      console.log(row, "我是每一个的row");
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get(
        `/admin/selectById/${row.row.adminId}`
      );
      console.log(res, "按照id查找管理员");
      this.editForm = res.data;
      this.imageUrl2 = res.data.url
    },
    editSuccess() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.put("/admin/updateById", {
            adminId: this.editForm.adminId,
            email: this.editForm.email,
            password: this.editForm.password,
            url:this.editForm.url
          });
          console.log(res, "我是修改之后的返回");
          if (res.data.flag == true) {
            this.$message.success("修改成功");
            this.editDialogVisible = false;
            this.getAdminList();
          } else {
            return this.$message.error("修改失败");
          }
        }
      });
    },
    deleteById(row) {
      console.log(row, "我是列数据用来删除的");
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.delete("/admin/delete/" + row.adminId);
          this.getAdminList();
          console.log(res, "我是删除之后的信息");
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //监听 pageesize 改变的事件
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.queryInfo.pagesize = newSize;
      this.getAdminList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.queryInfo.pagenum = newPage;
      this.getAdminList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //添加图片所用
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.url= res.data
      console.log(res,'.......')
      console.log(file,'............')
      
    },
    //这个用来编辑 回显
    handleAvatarSuccess2(res, file) {
      this.imageUrl2 = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.editForm.url= res.data
      console.log(res,'.......')
      console.log(file,'............')
      
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      //验证邮箱的正则表达式
      var regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    return {
      url:"",
      //用于添加
      imageUrl: "",
      //用于编辑
      imageUrl2: "",
      /* 添加用户表单 */
      addForm: {
        adminname: "",
        password: "",
        email: "",
        avatar_url: "",
        // mobile: '',
      },
      /*修改用户表单 */
      editForm: {
        adminId: 0,
        adminname: "",
        password: "",
        email: "",
        avatar_url: "",
      },
      //获取用户列表的参数对象
      queryInfo: {
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 3,
      },
      adminList: [],
      total: 0,
      multipleSelection: [],
      addDialogVisible: false,
      /* 编辑用户对话框是否显示 */
      editDialogVisible: false,
      /* 添加表单的验证规则 */
      addFormrules: {
        adminname: [
          { required: true, message: "请输入管理员名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail },
        ],
      },
      /* 修改表单的验证规则 */
      editFormRules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail },
        ],
      },
    };
  },
};
</script>

<style scoped>
.el-pagination {
  margin-top: 15px;
}
.el-card {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}
/* 添加头像的样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* .bottom{
  display: flex;
  justify-content: space-around;
} */
</style>